//
//  ZTLoadZYHTMLViewController.m
//  AFNetworking
//
//  Created by 武得亮 on 2021/3/12.
//

#import "ZTLoadZYHTMLViewController.h"
#import <WebKit/WebKit.h>
#import "NSString+ZTUrl.h"
#import "NSAttributedString+ZTEmotion.h"
#import "NSObject+ZTNotNull.h"
#import "ZTTopMoveButton.h"
#import "AFNetworking.h"
#import "Masonry.h"

#import "ZTHttpUrlDefine.h"
#import "ZTMacros.h"
#import "UIViewController+ZTHUD.h"

#import "ZTCraryUtils.h"
//#import "WPSTool.h"
#import "ZTJSFileModel.h"
#import "ZTUserInfoManage.h"

@interface ZTLoadZYHTMLViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView * webView;
@property (nonatomic, copy) NSString * dataUrl;//加载的url
@property (nonatomic, strong) ZTTopMoveButton *topCloseButton;
@property (nonatomic,strong) UIProgressView *progressView;

@end

@implementation ZTLoadZYHTMLViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.hostUrlString == nil) {
        self.hostUrlString = ZYHOST;
    }
    
    self.view.backgroundColor = [UIColor whiteColor];
//    self.fd_prefersNavigationBarHidden = YES;
    WKWebView * view = [[WKWebView alloc]init];
    view.scrollView.bounces = NO;
    view.navigationDelegate=self;
    view.opaque = NO;
    view.backgroundColor = [UIColor whiteColor];
    view.allowsBackForwardNavigationGestures=YES;
    NSString * urlTest = [self.hostUrlString stringByAppendingFormat:ZYLOGIN_URI,[[ZTUserInfoManage defaultService] getLoginUserAccount]];
    

 
//    [[ApiCenter defaultClient] postWithURLString:urlTest parameters:@{} success:^(BaseModel *model) {
//
//    } failure:^(NSError *error) {
//
//    }];
    
    
    _dataUrl = _url;
//    if ([self hasChinese:_url]) {
//        //处理URL中包含中文的情况
//        if (@available (iOS 8.0, *)) {
//            urlTest =  [_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        }else{
//            urlTest =  [_url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//        }
//    }else{
//        urlTest = _url;
//    }

    [view loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlTest]]];

    NSLog(@"-%@",urlTest);
    self.webView = view;
    self.webView.userInteractionEnabled = YES;
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    
    [self.view addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"webViewBackUpMethods"];
    
//    [self showHudInView:self.view hint:@"加载中..."];
    
    //获取文件名字和文件id
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"getFileMessage"];
    NSBundle *associateBunle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"ZTPrivateLib" ofType:@"bundle"]];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"chat_back"
                                                                                               inBundle: associateBunle
                                                                                             compatibleWithTraitCollection:nil] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:(UIBarButtonItemStylePlain) target:self action:@selector(backClick)];
//    self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 64+statusHeight, CGRectGetWidth(self.view.frame), 2)];
//    self.progressView.progressTintColor = [UIColor greenColor];
//    [self.view addSubview:self.progressView];
    [self showHudInView:self.view hint:@"加载中..."];
    // 给webview添加监听
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    [self.view addSubview:self.topCloseButton];
    self.topCloseButton.frame = CGRectMake(KScreenWidth - 60, 200, 53, 53);
}

// 监听事件处理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        if (self.webView.estimatedProgress  >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
//                [self.progressView setAlpha:0.0f];
                [self hideHud];
            } completion:^(BOOL finished) {
//                [self.progressView setProgress:0.0f animated:YES];
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *url = [navigationAction.request.URL absoluteString];
    if ([url containsString:ZYLOGIN_SUCCESS_URI]) {
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_dataUrl]]];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
    return;
}

- (void)dealloc{
    
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView setNavigationDelegate:nil];
    [self.webView setUIDelegate:nil];
}

- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)hasChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
     NSLog(@"开始请求");
}
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    NSLog(@"提交数据");
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSLog(@"请求完成");
//    [self hideHud];
//    if ([self.webView canGoBack] == YES) {
//        [self.webView goBack];
//    }else{
//        [self backClick];
//    }
    
    //    if ([_dataUrl hasSuffix:@".txt"]) {
    //        [self.webView goBack];
    //        [self backClick];
    //    }
    
//    [webView evaluateJavaScript:@"document.body.style.backgroundColor=\"#FFFFFF\"" completionHandler:nil];


}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self deleteWebCache];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)deleteWebCache {

    if([[UIDevice currentDevice].systemVersion floatValue] >=9.0) {
        
        NSSet*websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
        
        NSDate*dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        
        [[WKWebsiteDataStore defaultDataStore]removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            
        }];
        
    }else{
        
        NSString*libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES)objectAtIndex:0];
        
        NSString*cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        
        NSError*errors;
        
        [[NSFileManager defaultManager]removeItemAtPath:cookiesFolderPath error:&errors];
        
    }
    
}


- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (ZTTopMoveButton *)topCloseButton{
    if (!_topCloseButton) {
        _topCloseButton = [ZTTopMoveButton buttonWithType:UIButtonTypeCustom];
        NSBundle *associateBunle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"ZTPrivateLib" ofType:@"bundle"]];

        [_topCloseButton setImage:[UIImage imageNamed:@"ZTTopClose"
                                             inBundle: associateBunle
                                           compatibleWithTraitCollection:nil] forState:UIControlStateNormal];
        [_topCloseButton setImage:[UIImage imageNamed:@"ZTTopClose"
                                             inBundle: associateBunle
                                           compatibleWithTraitCollection:nil] forState:UIControlStateHighlighted];
        [_topCloseButton setImage:[UIImage imageNamed:@"ZTTopClose"
                                             inBundle: associateBunle
                                           compatibleWithTraitCollection:nil] forState:UIControlStateSelected];
        [_topCloseButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _topCloseButton;
}

#pragma mark- 关闭
- (void)closeAction{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getFileMessageAction:(NSString *)urlString{
    
    if(![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"KingsoftOfficeApp://"]]){
        [ZTCraryUtils showHudOnWindow:@"您没有安装WPS软件，仅能查看"];
        ZTLoadZYHTMLViewController *webVC = [[ZTLoadZYHTMLViewController alloc]init];
        webVC.url = urlString;
        webVC.webView.scrollView.scrollEnabled = YES;
        [self.navigationController pushViewController:webVC animated:YES];
        
        
        
    }else{
        
//        WPSTool *tool = [WPSTool shareInstance];
//        [tool openWPSWithUrl:urlString];
    }
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    if ([message.name isEqualToString:@"getFileMessage"]) {
        NSLog(@"openAppSelfMethods --- %@",message.body);
        
        NSArray *fileArray = message.body;
        NSString *urlString = [NSString stringWithFormat:@"%@/seeyon/rest/attachment/file/%@?fileName=%@",self.hostUrlString,fileArray[1],fileArray[0]];
        if ([self hasChinese:urlString]) {
            //处理URL中包含中文的情况
            urlString =  [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        }
        if ([urlString containsString:@".png"] || [urlString containsString:@".jpg"]) {
//            ZTLibSingleWebViewController *webVC = [[ZTLibSingleWebViewController alloc]init];
//            webVC.type = @"1";
//            webVC.urlString = urlString;
//            webVC.webView.scrollView.scrollEnabled = YES;
//            [self.navigationController pushViewController:webVC animated:YES];
//
            return ;
        }
        [self getFileMessageAction:urlString];
        ZTJSFileModel *model = [[ZTJSFileModel alloc] init];
//        WPSTool *tool = [WPSTool shareInstance];
//        if (fileArray.count >= 5) {
//            model.fileName = fileArray[0];
//            model.fileId = fileArray[1];
//            model.hostUrl = fileArray[2];
//            model.tokenString = fileArray[3];
//            model.authCode = fileArray[4];
//            tool.fileMd = model;
//        }
//        NSArray *body = message.body;
////        NSString *fileName = [body[0] stringByRemovingPercentEncoding];
//        NSString *fileId = body[1];
//
//        NSString *urlString = [NSString stringWithFormat:@"%@/seeyon/rest/attachment/file/%@",self.hostUrlString,fileId];
//
//        NSString *cookieString = [self cookieValue];
//        ZTSingleH5MethodsController *vc = [[ZTSingleH5MethodsController alloc]init];
//        vc.cookieValue = cookieString;
//        vc.urlString = urlString;
//
//        [self.navigationController pushViewController:vc animated:YES];
        
    }else if ([message.name isEqualToString:@"webViewBackUpMethods"]){//返回测试

        [self.navigationController popViewControllerAnimated:YES];

    }
    
}


#pragma mark - ------ 获取NSHTTPCookieStorage中我们要的cookie，以便去设置请求头 ------
- (NSString *)cookieValue{
    
    NSString * urlTest = [self.hostUrlString stringByAppendingFormat:ZYLOGIN_URI, [[ZTUserInfoManage defaultService] getLoginUserAccount]];


    
    NSArray *array = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:urlTest]];
    NSString *jessionIdString;
    for (NSHTTPCookie *cookie in array) {
        NSLog(@"-----------cookiename: %@ cookieValue: %@ cookieDomin: %@",cookie.name,cookie.value,cookie.domain);
        if ([cookie.name isEqualToString:@"JSESSIONID"]) {
            jessionIdString = cookie.value;
        }
    }
    
    NSString* cookieValue = [NSString stringWithFormat:@"JSESSIONID=%@",jessionIdString];
    return cookieValue;
}


#pragma mark - ------ 获取wkwebview的cookie，并且存储到NSHTTPCookieStorage ------
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    if (@available(iOS 11.0, *)) {//iOS11也有这种获取方式，但是我使用的时候iOS11系统可以在response里面直接获取到，只有iOS12获取不到
        WKHTTPCookieStore *cookieStore = webView.configuration.websiteDataStore.httpCookieStore;
        WEAK_SELF;
        [cookieStore getAllCookies:^(NSArray* cookies) {
            [weakSelf setCookie:cookies];
        }];
    }else {
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
        NSArray *cookies =[NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
        [self setCookie:cookies];
    }
    
    decisionHandler(WKNavigationResponsePolicyAllow);
}


-(void)setCookie:(NSArray *)cookies {
    if (cookies.count > 0) {
        for (NSHTTPCookie *cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
}


@end
